﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static 通讯录.Program;

namespace 通讯录
{
    public partial class Helloworld1 : Form
    {
        public Helloworld1()
        {
            InitializeComponent();
            InitializeData();
        }

        private void InitializeData(List<DataInfo> ls = null)
        {
            if (ls == null)
                ls = userLs;
            this.listBox1.Items.Clear();
            for (int i = 0; i < ls.Count; i++)
            {
                this.listBox1.Items.Add(ls[i].name + ":" + ls[i].phoneNumber);
            }
            this.lableUserAmount.Text = ls.Count == 0 ? "" : ls.Count.ToString();
        }


        /// <summary>
        /// save and update interface
        /// </summary>
        /// <param name="data"></param>
        /// <param name="state">0:add, 1:removed, 2:modify</param>
        void SaveAndUpdate(DataInfo data, byte state)
        {
            WriteData(data, state);
            txtSearch_TextChanged(null, null);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged_1(object sender, EventArgs e)
        {
            Regex re = new Regex("[^0-9]+");

        }

        private void keydown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Oemplus)
            {
                MessageBox.Show("do someing");
            }
        }
        private string pattern = @"^[0-9]*$";
        private string param1 = null;
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            Match m = Regex.Match(this.txtBoxNumber.Text, pattern);   // 匹配正则表达式

            if (!m.Success)   // 输入的不是数字
            {
                this.txtBoxNumber.Text = param1;   // textBox内容不变

                // 将光标定位到文本框的最后
                this.txtBoxNumber.SelectionStart = this.txtBoxNumber.Text.Length;
            }
            else   // 输入的是数字
            {
                param1 = this.txtBoxNumber.Text;   // 将现在textBox的值保存下来
            }
        }


        private void Add_Click(object sender, EventArgs e)
        {
            DataInfo data = new DataInfo();
            data.name = this.textBoxName.Text;
            Double.TryParse(this.txtBoxNumber.Text, out data.phoneNumber);
            this.listBox1.Items.Add(data.name + ":" + data.phoneNumber);
            SaveAndUpdate(data, 0);
            this.lableUserAmount.Text = serachUserLs.Count.ToString();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBox1.Items.Count > 0 && this.listBox1.SelectedIndex >= 0 && this.listBox1.SelectedIndex < this.listBox1.Items.Count)
            {
                DataInfo data = serachUserLs[this.listBox1.SelectedIndex];
                this.textBoxSRName.Text = data.name;
                this.searchNumber.Text = data.phoneNumber.ToString();
                DateTime t = new DateTime(data.id);
                this.labelUserId.Text = t.ToString("yyyy-MM-dd HH:mm:ss");
                this.editorPlane.Enabled = this.searchNumber.Enabled = this.textBoxSRName.Enabled = this.btnModify.Enabled = this.btnRemove.Enabled = true;
            }
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            string str = this.txtSearch.Text.Replace('，', ',');
            string[] arr = str.Split(',');
            serachUserLs = userLs;


            for (int i = 0; i < arr.Length; i++)
            {
                if (!String.IsNullOrEmpty(arr[i]))
                {
                    serachUserLs = serachUserLs.FindAll(delegate (DataInfo data)
                    {
                        bool contains = data.name.IndexOf(arr[i], StringComparison.OrdinalIgnoreCase) >= 0;
                        bool contains1 = data.phoneNumber.ToString().IndexOf(arr[i], StringComparison.OrdinalIgnoreCase) >= 0;
                        return contains || contains1;
                    });
                }
            }
            InitializeData(serachUserLs);
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (this.listBox1.Items.Count > 0 && this.listBox1.SelectedIndex >= 0 && this.listBox1.SelectedIndex < this.listBox1.Items.Count)
            {
                DataInfo data = serachUserLs[this.listBox1.SelectedIndex];
                serachUserLs.RemoveAt(this.listBox1.SelectedIndex);
                this.listBox1.Items.RemoveAt(this.listBox1.SelectedIndex);
                this.labelUserId.Text = this.textBoxSRName.Text = this.searchNumber.Text = "";
                this.editorPlane.Enabled = this.searchNumber.Enabled = this.textBoxSRName.Enabled = this.btnModify.Enabled = this.btnRemove.Enabled = false;
                this.lableUserAmount.Text = serachUserLs.Count == 0 ? "" : serachUserLs.Count.ToString();
                WriteData(data, 1);
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Delete && this.btnRemove.Enabled)
            {
                btnRemove_Click(this.btnRemove, null);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            if (this.listBox1.Items.Count > 0 && this.listBox1.SelectedIndex >= 0 && this.listBox1.SelectedIndex < this.listBox1.Items.Count)
            {
                DataInfo data = serachUserLs[this.listBox1.SelectedIndex];
                data.name = this.textBoxSRName.Text;
                Double.TryParse(this.searchNumber.Text, out data.phoneNumber);
                int lastChoose = this.listBox1.SelectedIndex;
                for (int i = 0; i < userLs.Count; i++)
                {
                    if (userLs[i].id == data.id)
                    {
                        userLs[i] = data;
                        break;
                    }
                }
                SaveAndUpdate(data, 2);
                this.listBox1.SelectedIndex = lastChoose;
            }
        }
    }
}
